/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.yaba.dbs.server;

import br.com.yaba.dbs.core.YabaData;
import br.com.yaba.dbs.core.Message;
import br.com.yaba.dbs.core.Chunk;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author emanuellfaustino
 */
public class ServerImpl {
    private int _port;
    
    public ServerImpl(int port) {
        _port = port;
    }
    
    public void listen() throws IOException {
        ServerSocket server = new ServerSocket(_port);
        
        while(true) {
            Socket socketClient = server.accept();
            YabaData dataToBackup = receivePackages(socketClient);
            
            String dataHash = backup(dataToBackup.getUserId(), dataToBackup);
            
            if(dataHash != null) {
                sendMessage(socketClient, Message.SUCESS, dataHash);
            } else {
                sendMessage(socketClient, Message.FAIL, "");
            }
        }
    }
    
    public YabaData receivePackages(Socket socketClient) throws IOException {
        ObjectInputStream input = new ObjectInputStream(socketClient.getInputStream());
        
        YabaData data = new YabaData("ID USER - MUDAR ISSO", "NOME DO ARQUIVO - MUDAR ISSO");
        int current = 0;
        int total = 0;
        
        do {
            
            Chunk aChunk = null;
            try {

                aChunk = (Chunk) input.readObject();
                data.add(aChunk);
                
                System.out.println("#SERVER# Received chunk: " + aChunk.getCurrentNumber() + "/" + aChunk.getTotal());
            } catch (ClassNotFoundException ex) {
                System.out.println(ex.getMessage());
            }
           
            current = aChunk.getCurrentNumber();
            total = aChunk.getTotal();
            
        } while(current != total);
        
        return data;
    }
    
    public String backup(String userId, YabaData data) {
        return "abc123";
    }
    
    public void sendMessage(Socket socketClient, int type, String msg) throws IOException {
        ObjectOutputStream output = new ObjectOutputStream(socketClient.getOutputStream());
        
        output.writeObject(new Message(type, msg));
        output.flush();
    }
    
    public void finishConnection(Socket socketClient) throws IOException {
        socketClient.close();
    }

}
